<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['project:group:add']"
          >创建楼栋</el-button
        >
      </el-col>
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="header"
    >
      <el-form-item>
        <el-select
          v-model="queryParams.groupId"
          placeholder="请选择所属企业"
          size="small"
          clearable
          class="affiliatedCompany"
        >
          <el-option
            v-for="dict in dict.type.ly_group"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择所属项目"
          size="small"
          clearable
          class="affiliatedProject"
        >
          <el-option
            v-for="item in queryProjectList"
            :label="item.projectName"
            :value="item.id"
            :key="item.id"
          >
            {{ item.projectName }}</el-option
          >
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input
          placeholder="楼栋名称"
          v-model="queryParams.banName"
          class="buildName"
          clearable
          @keyup.enter.native="handleQuery"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          placeholder="楼栋地址"
          v-model="queryParams.banAddress"
          class="buildAddress"
          clearable
          @keyup.enter.native="handleQuery"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-refresh"
          class="reset"
          size="mini"
          @click="resetQuery()"
          >重置</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-search"
          class="search"
          type="primary"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button
          class="export"
          type="warning"
          icon="el-icon-upload"
          size="mini"
          @click="handleExport"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="banDataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="楼栋名称" align="center" prop="banName" />
      <el-table-column label="所属企业" align="center" prop="groupId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ly_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="楼栋地址" align="center" prop="banAddress" />
      <el-table-column label="总楼层数" align="center" prop="banNumbers" />
      <el-table-column label="总面积(㎡)" align="center" prop="banArea" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateOrDetail(scope.row, '编辑')"
            v-hasPermi="['project:project:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdateOrDetail(scope.row, '详情')"
            v-hasPermi="['project:project:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改[空间] 楼宇对话框 -->
    <el-dialog
      :fullscreen="true"
      :center="true"
      :title="title"
      :visible.sync="open"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="dialog-content">
          <el-form-item label="楼栋名称" prop="banName">
            <el-input
              v-model="form.banName"
              :style="{ width: '33%' }"
              :readonly="title === '详情'"
            />
          </el-form-item>
          <el-form-item label="所属项目" prop="projectId">
            <div class="project_content">
              <el-input
                placeholder="点击查询"
                :readonly="true"
                v-model="form.projectName"
              ></el-input>
              <el-button
                type="text"
                class="project-select-button"
                @click="projectSelect"
                v-if="title !== '详情'"
                >查询</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="楼栋地址" prop="banAddress">
            <el-input
              v-model="form.banAddress"
              :style="{ width: '33%' }"
              :readonly="title === '详情'"
            />
          </el-form-item>
          <el-form-item label="总楼层数" prop="banNumbers">
            <el-input
              v-model="form.banNumbers"
              :style="{ width: '33%' }"
              :readonly="title === '详情'"
            />
          </el-form-item>
          <el-form-item label="总面积" prop="banArea">
            <el-input
              v-model="form.banArea"
              :style="{ width: '33%' }"
              :readonly="title === '详情'"
            >
              <template slot="append">m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="实景图">
            <el-upload
              multiple
              :file-list="fileList"
              list-type="picture-card"
              :action="uploadUrl"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :disabled="title === '详情'"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !== '详情'"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="项目查询器" width="60%" :visible.sync="openProjectSelect">
      <ProjectManagement ref="projectRef" :is-component="true" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelProjectSelect">取 消</el-button>
        <el-button type="primary" @click="confirmProjectSelect"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBan,
  getBan,
  delBan,
  addBan,
  updateBan,
  exportBan,
} from "@/api/space/ban";
import ProjectManagement from "@/views/project/projectManagement/index.vue";
import { getAllProjectsApi, getBanByProjectId } from "@/api/space/workSpace";

export default {
  name: "Ban",
  // 数据字典
  dicts: ["ly_group"],
  components: { ProjectManagement },

  data() {
    return {
      name: "",
      address: "",
      // 表格数据
      banDataList: [],
      // 楼栋列表
      banList: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用于查询的所有项目列表
      queryProjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 项目选择器弹出层
      openProjectSelect: false,
      // 文件上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/ly/fileUpload",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        banName: null,
        projectId: null,
        banAddress: null,
      },
      // 表单参数
      form: {},
      // 图片上传列表
      fileList: [],
      // 表单校验
      rules: {
        banName: [
          { required: true, message: "楼栋名称不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "blur" },
        ],
        banAddress: [
          { required: true, message: "楼栋地址不能为空", trigger: "blur" },
        ],
        banNumbers: [
          { required: true, message: "总楼层数不能为空", trigger: "blur" },
        ],
        banArea: [
          { required: true, message: "楼宇面积不能为空", trigger: "blur" },
        ],
      },
      imgs: [],
    };
  },
  created() {
    this.getList();
    this.getAllProjects();
  },
  methods: {
    /** 创建楼栋 */
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建楼栋";
    },
    // 表单重置
    reset() {
      this.form = {
        banId: null,
        groupId: null,
        projectId: null,
        projectName: null,
        banName: null,
        banNumbers: null,
        banArea: null,
        banAddress: null,
        imgs: [],
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 查询[空间] 楼宇列表 */
    getList() {
      this.loading = true;
      listBan(this.queryParams).then((response) => {
        this.banDataList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    //取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        banName: null,
        groupId: null,
        projectId: null,
        banAddress: null,
      };
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.banId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查询项目信息 */
    projectSelect() {
      this.openProjectSelect = true;
    },
    /** 取消查询项目信息 */
    cancelProjectSelect() {
      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 确认项目 */
    confirmProjectSelect() {
      const currentProject = this.$refs.projectRef.getCurrentProject();
      this.form.projectId = currentProject.id;
      this.form.projectName = currentProject.projectName;
      this.form.groupId = currentProject.groupId;
      // 获取该项目的所有楼栋信息
      this.getBanList(this.form.projectId);

      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 编辑或详情按钮操作 */
    handleUpdateOrDetail(row, title) {
      this.reset();
      // 获取楼栋详情
      getBan(row.banId).then((response) => {
        this.form = response.data;
        this.form.projectId = row.projectId;
        this.form.projectName = row.projectName;
        this.form.imgs = this.fileList = JSON.parse(response.data.imgs);

        this.title = title;
        this.open = true;
      });
    },

    /** 获取楼栋列表 */
    getBanList(projectId) {
      getBanByProjectId(projectId).then((res) => {
        this.banList = res.code === 200 ? res.data : [];
      });
    },
    /** 查询所有项目列表用于筛选 */
    getAllProjects() {
      getAllProjectsApi().then((res) => {
        this.queryProjectList = res.code === 200 ? res.data : [];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.imgs = JSON.stringify(this.form.imgs);
          if (this.form.banId != null) {
            updateBan(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBan(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleSuccess(response, file, fileList) {
      console.log(file);
      this.form.imgs.push({ name: file.name, url: response.data });
    },
    handleRemove(file) {
      console.log(file);
      ``;
      this.form.imgs = this.form.imgs.filter((item) => item.url !== file.url);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const banId = row.banId || this.ids;
      this.$modal
        .confirm('是否确认删除楼栋编号为"' + banId + '"的数据项？')
        .then(function () {
          return delBan(banId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportBan().then((res) => {
        // 创建 Blob 对象，用于包含二进制数据
        const blob = new Blob([res]);
        // 创建 a 标签元素，并将 Blob 对象转换成 URL
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        // 设置下载文件的名称
        const date = new Date();
        const now = date.toLocaleDateString();
        link.download = "楼栋数据_" + now + "_.xlsx";
        // 模拟点击下载链接
        link.click();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 5px;
  .affiliatedProject {
    margin-left: 7px;
  }

  .buildName {
    width: 135px;
    margin-left: 7px;
  }

  .buildAddress {
    width: 135px;
    margin-left: 7px;
  }

  .reset {
    margin-left: 7px;
  }
}

.affiliatedProject {
  margin-left: 7px;
  border: rgb(210, 210, 210);
}

.project_content {
  display: flex;
  align-items: center;
  position: relative;
  width: 591px;

  .project-select-button {
    position: absolute;
    right: 10px;
  }
}

.buildName {
  width: 135px;
  margin-left: 20px;
}

.buildAddress {
  width: 135px;
  margin-left: 20px;
}

.reset {
  margin-left: 10px;
}
</style>
